import os
from Queue import Empty

from EpisodeUtil import EpisodeUtil
from EpisodeRegex import EpisodeRegex
from NFO import NFO
from TVDB import TVDB


class Scraper(object):
            
    def __init__(self, dir, tvdb_code, extensions=None):
        self.sourceDir = dir
        self.tvdb = TVDB(tvdb_code)
        self.__regex = EpisodeRegex(extensions)
        self.__eParser = EpisodeUtil()
        self.force = False
            
    def scrap(self):
        self.scraped = self.__search_for_files_to_scrap()
        self.__scrape_episodes()

    def __search_for_files_to_scrap(self):
        toScrape = []
        for file in os.listdir(self.sourceDir):
            eps = self.__search_eps_to_scrap(file)
            if self.__is_able_to_scrape(eps):
                toScrape.append(eps)
        return toScrape
                    
    def __is_able_to_scrape(self, eps):       
        if eps is not None:
            epsFileName = eps.getFileName()+".nfo"
            nfoFilePath = os.path.join(self.sourceDir, epsFileName)
            nfoExists = os.path.exists(nfoFilePath)
            return self.force or not nfoExists 
        else:
            return False
        
    #TODO: Add throw exception
    def __search_eps_to_scrap(self, file):
        match = self.__regex.search(file)
        if match != None:
            return self.__eParser.createFromMatch(match)
        return None
    
    def __scrape_episodes(self):
        if self.scraped is not Empty:
            serieData = self.tvdb.get_data()
            for episode in self.scraped:
                self.__scrape_episode(episode, serieData)
                    
    def __scrape_episode(self, episode, serieData):
        absoluteNumber = episode.absoluteNumber
        episodeData = serieData.findall("Episode[absolute_number='"+absoluteNumber+"']")
        if self.__has_valid_data(episodeData[0]):
            neps = self.__load_episode(episode, episodeData[0])
            self.__create_nfo_file(neps)
                    
    def __load_episode(self, episode, episodeData): 
        return self.__eParser.loadFromXml(episode, episodeData)
    
    def __create_nfo_file(self, episode):
        nfo = NFO(episode, self.sourceDir)
        nfo.save()
        
    def __has_valid_data(self, data):
        return data[0] != None